package com.juzhencms.apps.busi.web;

import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.juzhencms.apps.base.busi.entity.BasicLoginUser;
import com.juzhencms.apps.base.busi.service.WeixinApiService;
import com.juzhencms.apps.base.common.config.Config;
import com.juzhencms.apps.base.common.database.DBTable;
import com.juzhencms.apps.base.common.util.StringUtil;
import com.juzhencms.apps.base.common.util.WebUtil;
import com.juzhencms.apps.busi.service.AppWeixinSourceService;
import com.juzhencms.apps.busi.service.SiteService;
import com.juzhencms.apps.busi.service.UserService;

import lombok.extern.slf4j.Slf4j;


@Controller
@RequestMapping("/appMessage")
@Slf4j
public class AppMessageController  extends BaseController{
	
	@Autowired
	private AppWeixinSourceService appWeixinSourceService;
	
	
	@Autowired
	private WeixinApiService weixinApiService;
	@Autowired
	private  SiteService siteService;
	
	@Autowired
	private UserService userService;
	@RequestMapping(value="/gridlistData",produces="text/html; charset=UTF-8")
	@ResponseBody
	public String gridlistData(HttpServletRequest request){
		Map data=new HashMap();
		List whereParamList=new ArrayList();
		String where=" where m.del_flag=0 and m.site_id in("+this.getUserService().getLoginUser().getSiteIds()+") ";
		//String where=" where del_flag=0 ";
		//搜索参数
		if(request.getParameter("title")!=null && !request.getParameter("title").toString().trim().equals("")){
			where+=" and m.title like ? ";
			whereParamList.add("%"+request.getParameter("title")+"%");
		}
		
		if(StringUtil.isNotNullOrEmpty(request.getParameter("status"))) {
			where+=" and m.status= ? ";
			whereParamList.add(request.getParameter("status"));
		}
		
		/*	if(StringUtil.isNotNullOrEmpty(request.getParameter("site_id"))) {
				where+=" and site_id like ? ";
				whereParamList.add("%,"+request.getParameter("site_id")+",%");
			}*/
		
		if(StringUtil.isNotNullOrEmpty(request.getParameter("site_id"))) {
			where+=" and m.site_id=?";
			whereParamList.add(request.getParameter("site_id"));
		}
		
		
		if(request.getParameter("create_time_from")!=null && !request.getParameter("create_time_from").toString().trim().equals("")){
			where+=" and m.create_time >= ? ";
			whereParamList.add(request.getParameter("create_time_from"));
		}
		
		if(request.getParameter("create_time_to")!=null && !request.getParameter("create_time_to").toString().trim().equals("")){
			where+=" and m.create_time <= ? ";
			whereParamList.add(request.getParameter("create_time_to"));
		}
		
		
		
		
		//分页处理
		int pageIndex=1;
		if(request.getParameter("pageIndex")!=null && !request.getParameter("pageIndex").toString().trim().equals("")){
			pageIndex=new Integer(request.getParameter("pageIndex")).intValue();
		}
		int pageSize=10;
		if(request.getParameter("pageSize")!=null && !request.getParameter("pageSize").toString().trim().equals("")){
			pageSize=new Integer(request.getParameter("pageSize")).intValue();
		}
		int start=0;
		if(pageIndex>1){
			start=(pageIndex-1)*pageSize;
		}
		whereParamList.add(start);
		whereParamList.add(pageSize);
		
		//排序参数 
		String sortField="m.id";
		String sortOrder="desc";
		if(request.getParameter("sortField")!=null && !request.getParameter("sortField").equals(""))
			sortField = "m."+request.getParameter("sortField");
		if(request.getParameter("sortOrder")!=null && !request.getParameter("sortOrder").equals(""))
			sortOrder = request.getParameter("sortOrder");
		
		//查询列表数据
		List dataList=this.getCommonService().getJdbcDao().querySql("select m.*,s.name as site_name from "+DBTable.appMessage+" as m left join "+DBTable.site+" as s on m.site_id=s.id "+where+" order by "+sortField+" "+sortOrder+" limit ?,?", whereParamList.toArray());
		if(dataList!=null && dataList.size()>0){
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			for(int i=0;i<dataList.size();i++){
				Map row=(Map)dataList.get(i);
				if(row.get("create_time")!=null) {
					Date date = (Date)row.get("create_time");
					row.put("create_time",sdf.format(date));
				}
				//查询所属部门
				Map user=this.getCommonService().getJdbcDao().queryRow("select user,name from "+DBTable.user+" where id=? ", new Object[] {row.get("create_user")});
				if(user!=null) {
					row.put("create_user",user.get("user"));
				}
			}
		}
		
		//查询总条数
		Map countRow=this.getCommonService().getJdbcDao().queryRow("select count(m.id) as count_num from "+DBTable.appMessage+" as m  "+where, whereParamList.subList(0, whereParamList.size()-2).toArray());
		int recordsTotal=0;
		if(countRow.get("count_num")!=null){
			recordsTotal=new Integer(countRow.get("count_num").toString()).intValue();
		}
		
		//拼装返回的数据
		data.put("data", dataList.toArray());
		data.put("itemsCount", recordsTotal);
		
		
		return WebUtil.resultString(data,request);
	}
	
	@RequestMapping(value="/detailData/{id}",produces="text/html; charset=UTF-8")
	@ResponseBody
	public String detailData(@PathVariable("id") String id,HttpServletRequest request){
		Map data=new HashMap();
		Map record=this.getCommonService().getJdbcDao().queryRow("select * from "+DBTable.appMessage+" where id=?",new Object[]{id});	
        if(record!=null && record.size()>0) {
            List newsList =new ArrayList();
        	List siteList=new ArrayList();
        	String status=record.get("status")+"";
        	if("0".equals(status)) { //没有发送        		
        		 record.put("edit", "1");	
        	}else {
        		
        		//发送结果
        		String sendResult="msg："+record.get("errmsg");
        		if(StringUtil.isNotNullOrEmpty(record.get("msg_id"))) {
        			 sendResult+="\n"+"msg_id："+record.get("msg_id")+"\n"+"msg_data_id："+record.get("msg_data_id");
        		}
        		record.put("sendResult", sendResult);
        		record.put("edit", "0");	
        	}
        	
        	String data_id=record.get("data_id")+"";
    		String[] dataList = data_id.split(",");	
    		
    		
    		
    	/*	String sql="select id,name,hits,publish,recommend,position,create_user,create_time,image from "+DBTable.news+" where del_flag=0 and id in(";
    		ArrayList whereParam = new ArrayList();
    		 for (int i=0 ;i<dataList.length; i++) {
  	            if(dataList[i]!=null && dataList[i].length()!=0){ //过滤掉数组arrayString里面的空字符串
  	            	sql+=" ?,";
  	            	whereParam.add(dataList[i]);
  	            }
  	         }
    		 sql= sql.substring(0,sql.length() - 1);
    		 sql+=")";
    		 newsList = this.getCommonService().getJdbcDao().querySql(sql, whereParam.toArray());
    		 if(newsList!=null && newsList.size()>0) {
    			 for(int i=0;i<newsList.size();i++) {
    				 Map newsInfo=(Map) newsList.get(i);
    				 if(StringUtil.isNotNullOrEmpty(newsInfo.get("image"))) {
  						newsInfo.put("_image",Config.getUploadUrlPath()+"/"+newsInfo.get("image"));
  					}else newsInfo.put("_image",Config.getUploadUrlPath()+"/nophoto.jpg");
    			 }        			
    		 }        
    		 */
    		 
    		if(dataList.length>0) {
    			 for (int i=0 ;i<dataList.length; i++) {
    	  	            if(dataList[i]!=null && dataList[i].length()!=0){ //过滤掉数组arrayString里面的空字符串
    	  	            	String sql="select id,name,hits,publish,recommend,position,create_user,create_time,image from "+DBTable.news+" where del_flag=0 and id=?";
    	  	            	Map newsInfo=this.getCommonService().getJdbcDao().queryRow(sql,new Object[] {dataList[i]});
    	  	            	if(newsInfo!=null && newsInfo.size()>0) {
    	  	            		if(StringUtil.isNotNullOrEmpty(newsInfo.get("image"))) {
    	  	  						newsInfo.put("_image",Config.getUploadUrlPath()+"/"+newsInfo.get("image"));
    	  	  					}else newsInfo.put("_image",Config.getUploadUrlPath()+"/nophoto.jpg");
    	  	            		newsList.add(newsInfo);
    	  	            	}
    	  	            }
    	  	      }
    		}
    		
    		 
    		 
    		 
    		 record.put("newsList", newsList);
    		 String whereStr="  del_flag=0 and id in (";
    		 String site_id=record.get("site_id")+"";
    		 String[] siteIdList = site_id.split(",");
    		 ArrayList whereParamList=new ArrayList();
    		 for (int i=0;i<siteIdList.length;i++) {
   	            if(siteIdList[i]!=null && siteIdList[i].length()!=0){ //过滤掉数组arrayString里面的空字符串
   	            	whereStr+="?,";
   	            	whereParamList.add(siteIdList[i]);
   	            }
   	         }
    		 whereStr= whereStr.substring(0,whereStr.length() - 1);
    		 whereStr+=")";
    		 
    		 siteList=this.siteService.getLists("name,id,weixin_no", whereStr, whereParamList, null, 0, 0, 0);
    		 record.put("siteList", siteList);
        	
        	
        }
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		Date date = (Date)record.get("create_time");
		record.put("create_time",sdf.format(date) );
		data.put("data", record);
		return WebUtil.resultString(data,request);
	}
	
	@RequestMapping(value="/save",produces="text/html; charset=UTF-8")
	@ResponseBody
	public String save(HttpServletRequest request){
		Map data = JSON.parseObject(request.getParameter("data"), Map.class); 
		String id=null;
		if(data.get("id")!=null){
			id=data.get("id").toString();
		}	
		String siteIdStr="";
		Map result=new HashMap();
		List siteList=new ArrayList();
		if(data.get("siteList")!=null) {
			 siteList = (List) data.get("siteList");
			 if(siteList.size()>0) {
				 siteIdStr+=",";
				 for(int i=0;i<siteList.size();i++) {
					 Map row=(Map) siteList.get(i);
					 siteIdStr+=row.get("id")+",";
				 }
			 }
		}
		if(siteList.size()==0) {
			result.put("result", 0);
			result.put("msg", "请选择要推送的公众号");		
			return WebUtil.resultString(result,request);
		}
		List newsList=new ArrayList();
		//String data_id="";
		if(data.get("newsList")!=null) {
			newsList = (List) data.get("newsList");
			if(newsList!=null && newsList.size()>0) {
				//data_id+=",";
				for(int i=0;i<newsList.size();i++) {
					Map row=(Map) newsList.get(i);
					//data_id+=row.get("id")+",";
				}
			}
		}
		if(newsList.size()==0) {
			result.put("result", 0);
			result.put("msg", "请选择要推送的文章");		
			return WebUtil.resultString(result,request);
		}
		if(data.get("create_time")==null || data.get("create_time").equals("")){
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date date = new Date();
			data.put("create_time", sdf.format(date));
		}
		BasicLoginUser loginUser=userService.getLoginUser();
		if(data.get("create_user")==null || data.get("create_user").equals("")){
			data.put("create_user",loginUser.getId());
		}
		
		String title="";
		if(StringUtil.isNotNullOrEmpty(data.get("title"))) {
			 title=data.get("title")+"";
		}	
		if(StringUtil.isNotNullOrEmpty(id) && !"0".equals(id)){ //编辑
			if(siteList.size()>1) {
				result.put("result", 0);
				result.put("msg", "请重新创建数据！");		
				return WebUtil.resultString(result,request);
			}
		}
		String saveAndSend=data.get("send")+"";		
		Date date = new Date();			
		for(int i=0;i<siteList.size();i++) {
			Map row=(Map) siteList.get(i);	
			//Map newsSource=new HashMap();
			int site_id=new Integer(row.get("id")+"");
			Map siteInfo=this.siteService.getDetail(site_id, "weixin_appid,weixin_appsecret,id");
			if(siteInfo!=null && siteInfo.size()>0) { 
			    row.putAll(siteInfo);				
				Map weiXinNews = this.appWeixinSourceService.addWeiXinNewsSource(site_id, newsList);
				String resultStr = weiXinNews.get("result")+"";
				if(weiXinNews!=null && "1".equals(resultStr)) {
					//newsSource.putAll(weiXinNews);
					row.put("newsSource", weiXinNews);					
				}else {
					result.put("result", 0);
					result.put("msg", weiXinNews.get("msg"));	
					return WebUtil.resultString(result,request); 
				}
			}else {
				result.put("result", 0);
				result.put("msg","微信公众号获取失败");	
				return WebUtil.resultString(result,request); 
			}
		}					
		for(int i=0;i<siteList.size();i++) {
			Map row=(Map) siteList.get(i);	
			Map newsSource=(Map) row.get("newsSource");
			int site_id=new Integer(row.get("id")+"");
			Map dataInfo=new HashMap();	
			dataInfo.put("title", title);
			dataInfo.put("data_id", newsSource.get("news_id"));
			dataInfo.put("message_type", data.get("message_type"));
			dataInfo.put("weixin_source_id",newsSource.get("id"));
			dataInfo.put("media_id",newsSource.get("media_id"));
			if("1".equals(saveAndSend)) { //
				//调用推送消息接口
				Map param=new HashMap();
				param.put("weixin_appid", row.get("weixin_appid"));
				param.put("weixin_appsecret", row.get("weixin_appsecret"));
				param.put("media_id", newsSource.get("media_id"));
				Map sendResult=this.weixinApiService.sendMessageToAll(param);
				/*	dataInfo.put("msg_id",sendResult.get("msg_id"));
					dataInfo.put("msg_data_id",sendResult.get("msg_data_id"));*/
				if("1".equals(sendResult.get("result")+"")) {
					dataInfo.put("status",1);
				}else { //发送失败
					dataInfo.put("status",2);
				}
				dataInfo.put("send_time", date);
				dataInfo.put("send_user",loginUser.getId());
				if(StringUtil.isNotNullOrEmpty(sendResult.get("msg_id"))) {
					dataInfo.put("msg_id",sendResult.get("msg_id"));
					dataInfo.put("msg_data_id",sendResult.get("msg_data_id"));
				}
				dataInfo.put("errmsg",sendResult.get("errmsg")+"");
			}else { //只做保存
				dataInfo.put("is_fixed",data.get("is_fixed"));
				dataInfo.put("fixed_time",data.get("fixed_time"));
			}
			if(StringUtil.isNotNullOrEmpty(id) && !"0".equals(id)) { //编辑数据	
				dataInfo.put("id", id);
				this.getCommonService().getJdbcDao().updateObj(DBTable.appMessage, dataInfo, "id");
			}else {
				dataInfo.put("site_id", site_id);
				dataInfo.put("create_time", data.get("create_time"));
				dataInfo.put("create_user", data.get("create_user"));
				this.getCommonService().getJdbcDao().addObj(DBTable.appMessage, dataInfo);
			}
		}		
		result.put("result", 1);
		result.put("msg", "保存成功");		
		return WebUtil.resultString(result,request);
		
	}
	
	@RequestMapping(value="/delete",produces="text/html; charset=UTF-8")
	@ResponseBody
	public String delete(HttpServletRequest request){

		
		Map data = JSON.parseObject(request.getParameter("data"), Map.class); 
		
		String id=null;
		if(data.get("id")!=null){
			id=data.get("id").toString();
		}
		
		
		if(id==null || id.equals("")){
		}else{	
	        String[] idArray = id.split(",");
	        String tmpVar="?";
	        if(idArray!=null && idArray.length>0){
	        	Matcher matcher = Pattern.compile("\\d+").matcher(id);
	        	tmpVar=matcher.replaceAll("?");
	        }
	        
	        
	        
			this.getCommonService().getJdbcDao().updateSql("update "+DBTable.appMessage+" set del_flag=1 where id in ("+tmpVar+")",idArray);
		}
		Map result=new HashMap();
		result.put("result",1);
		result.put("msg", "操作成功");
		
		return WebUtil.resultString(result,request);
	}
	
	@RequestMapping(value="/updatePosition",produces="text/html; charset=UTF-8")
	@ResponseBody
	public String updatePosition(HttpServletRequest request){
		
		if(request.getParameter("position")==null || request.getParameter("id")=="")
			return "";
		
		this.getCommonService().getJdbcDao().updateSql("update "+DBTable.appMessage+" set position=? where id=?",new Object[]{request.getParameter("position"),request.getParameter("id")});
		Map result=new HashMap();
		result.put("result",1);
		result.put("msg", "操作成功");
		
		return WebUtil.resultString(result,request);
	}
	
	@RequestMapping(value="/exportExcel",produces="text/html; charset=UTF-8")
	@ResponseBody
	public String exportExcel(HttpServletRequest request,HttpServletResponse response){
		
		
		Map data=new HashMap();
		List whereParamList=new ArrayList();
		String where="where del_flag=0";
		//搜索参数
		if(request.getParameter("name")!=null && !request.getParameter("name").toString().trim().equals("")){
			where+=" and name like ? ";
			whereParamList.add("%"+request.getParameter("name")+"%");
		}
		
		if(request.getParameter("publish")!=null && !request.getParameter("publish").toString().trim().equals("")){
			where+=" and publish = ? ";
			whereParamList.add(request.getParameter("publish"));
		}
		
		if(request.getParameter("create_time_from")!=null && !request.getParameter("create_time_from").toString().trim().equals("")){
			where+=" and create_time >= ? ";
			whereParamList.add(request.getParameter("create_time_from"));
		}
		
		if(request.getParameter("create_time_to")!=null && !request.getParameter("create_time_to").toString().trim().equals("")){
			where+=" and create_time <= ? ";
			whereParamList.add(request.getParameter("create_time_to"));
		}
		
		//分页处理
		int pageIndex=1;
		if(request.getParameter("pageIndex")!=null && !request.getParameter("pageIndex").toString().trim().equals("")){
			pageIndex=new Integer(request.getParameter("pageIndex")).intValue();
		}
		int pageSize=10;
		if(request.getParameter("pageSize")!=null && !request.getParameter("pageSize").toString().trim().equals("")){
			pageSize=new Integer(request.getParameter("pageSize")).intValue();
		}
		int start=0;
		if(pageIndex>1){
			start=(pageIndex-1)*pageSize;
		}
		whereParamList.add(start);
		whereParamList.add(pageSize);
		
		//排序参数
		String sortField="position";
		String sortOrder="asc";
		if(request.getParameter("sortField")!=null && !request.getParameter("sortField").equals(""))
			sortField = request.getParameter("sortField");
		if(request.getParameter("sortOrder")!=null && !request.getParameter("sortOrder").equals(""))
			sortOrder = request.getParameter("sortOrder");
		
		//查询列表数据
		List dataList=this.getCommonService().getJdbcDao().querySql("select * from "+DBTable.appMessage+" "+where+" order by "+sortField+" "+sortOrder+" limit ?,?", whereParamList.toArray());
		if(dataList!=null && dataList.size()>0){
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			for(int i=0;i<dataList.size();i++){
				Map row=(Map)dataList.get(i);
				if(row.get("create_time")!=null) {
					Date date = (Date)row.get("create_time");
					row.put("create_time",sdf.format(date));
				}
			}
		}
		
		//查询总条数
		Map countRow=this.getCommonService().getJdbcDao().queryRow("select count(id) as count_num from "+DBTable.appMessage+" "+where, whereParamList.subList(0, whereParamList.size()-2).toArray());
		int recordsTotal=0;
		if(countRow.get("count_num")!=null){
			recordsTotal=new Integer(countRow.get("count_num").toString()).intValue();
		}
		
		//拼装返回的数据
		data.put("data", dataList.toArray());
		data.put("itemsCount", recordsTotal);
		
		
		return WebUtil.resultString(data,request);
	}
	
}
